$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'water/prodata/list',
        datatype: "json",
        postData:{
            pro_name:vm.q.dept,
            clientId:vm.q.cid,
            clientName:vm.q.cname,
            clientAddress:vm.q.caddr,
            deviceStatus:vm.q.cstatus,
            deviceId:vm.q.deviceId,
            nowDate:vm.q.date1,
        },
        colModel: [
            { label: '设备号', name: 'deviceId', index: 'device_id', width: 120,  key: true },
			{ label: '表卡编号', name: 'clientId', index: 'client_id', width: 80 },
            { label: '客户姓名', name: 'clientName', index: 'client_name', width: 80 },
            { label: '客户地址', name: 'clientAddress', index: 'client_address', width: 150 },
            { label: '备注2', name: 'memo2', index: 'memo2', width: 60},
            { label: '采集日期', name: 'nowDate', index: 'now_date', width: 100
                ,formatter: function(value, options, row){
                    if (value == null) return "";
                    var cellvalue = value.substring(11,23);
                    return cellvalue;
                }},
            { label: '采集数据', name: 'nowData', index: 'now_data', width: 60},
            { label: '仪表状态', name: 'deviceStatus', index: 'device_status', width: 80 },
            { label: '设备地址', name: 'deviceAddress', index: 'device_address', width: 80
                ,formatter: function(value, options, row){
                    if (value == null) return "";
                    var dev = value.split("-");
                    var cellvalue = dev[dev.length-2]+'-'+dev[dev.length-1];
                    var memo1 = row.proName;
                    if (!(memo1.indexOf('CAT')>=0 || memo1.indexOf('NB')>=0 || memo1.indexOf('CCE')>=0
                        || memo1.indexOf('别墅')>=0 || memo1.indexOf('网点')>=0)){
                        cellvalue = dev[0]+'-'+dev[1]+'-'+dev[2]+'-'+cellvalue;
                    }
                    return cellvalue;
                } },
            { label: '仪表类型', name: 'typeName', index: 'type_name', width: 100 },
			//{ label: '状态码', name: 'statusCode', index: 'status_code', width: 40 },

            { label: 'IMEI', name: 'imei', index: 'imei', width: 60,hidden:true},
            { label: '户号', name: 'hourseNum', index: 'hourse_num', width: 60,hidden:true},
            { label: '质保开始日期', name: 'warrantyStart', index: 'warranty_start', width: 60,hidden:false},
            { label: '现场记录', name: 'recordOnSpot', index: 'record_on_spot', width: 60,hidden:false},
            { label: '唯一码', name: 'unkey', index: 'unkey', width: 80, key: true,hidden:true},

            { label: '备注', name: 'memo1', index: 'memo1', width: 60,hidden:true }
        ],
		viewrecords: true,
        height: $(window).height()-160 > 385 ?  $(window).height() - 160 : 385,
        rowNum: 100,
		rowList : [10,30,50,100],
        rownumbers: true, 
        rownumWidth: 55,
        autowidth:true,
        //multiselect: true,
        footerrow: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        ondblClickRow: function(rowid, iRow, iCol, e){
            $("#jqGrid").jqGrid('resetSelection');
            //$("#jqGrid").jqGrid('setSelection',$("#selRow").val(),false);
            $("#jqGrid").jqGrid('setSelection',rowid);

            vm.openInfoLayer($("#jqGrid").jqGrid("getRowData", rowid));

            $('#myTab a:first').tab('show');
        },
        onSelectRow: function (rowid, status) {
            // 当前选中行，用于页面调用reloadJqGrid刷新后，继续选中之前选中的
            vm.openInfoLayer($("#jqGrid").jqGrid("getRowData", rowid));

            $('#myTab a:first').tab('show');
        },
        onClickRow: function(rowid, iRow, iCol, e){

        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	//$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });

            //var rows = $("#jqGrid").jqGrid("getRowData"), total_count = 0;
            //想获取所有行 ,发现少一行
            //var allCountID = $("#jqGrid").jqGrid('getDataIDs');
            //rows.push($("#jqGrid").jqGrid('getRowData', allCountID[allCountID.length-1]));

            var ids = $("#jqGrid").getDataIDs(), total_count = 0;
            for(var i = 0; i<ids.length; i++) {
                var rowData = $("#jqGrid").getRowData(ids[i]);
                total_count += (rowData.deviceStatus == '正常' ? 1 : 0);
                if (rowData.deviceStatus != '正常'){
                    $("#jqGrid").find('#' + ids[i]).find("td").addClass("errrow");
                }
            }

            $("#jqGrid").jqGrid("footerData", "set", {
                clientName:"本页汇总:",
                clientAddress:"正常：" + total_count,
                typeName:"故障："+ (ids.length-total_count)
            });
        }
    });

    $('#datetimepicker1').datetimepicker({
        format: 'YYYY.MM.DD',
        locale: moment.locale('zh-cn')
    });
});

function zTreeOnDblClick(event, treeId, treeNode) {
    vm.q.dept = treeNode.deptId;
    vm.newpage = true;
    if(!treeNode.isParent) {
        var x = treeNode.deptId.split("_");
        if (x.length == 4){
            vm.q.dept = x[3];
            vm.getDataDate();
            //vm.reload();
        }
        // vm.reload();
    }
    //alert(treeNode.deptId);
    //alert(treeNode ? treeNode.tId + ", " + treeNode.name : "isRoot");
};

var settingLeft = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url:"nourl"
        }
    },
    callback: {
        onDblClick: zTreeOnDblClick,
        onClick:zTreeOnDblClick
    }
};

var ztree;

var vm = new Vue({
	el:'#rrapp',
	data:{
        q:{
            cid:null,
            cname:null,
            caddr:null,
            cstatus:'',
            dept:null,
            deviceId:null,
            date1:'',
        },
		showList: true,
		title: null,
        newpage : false,
		proData: {},
        dataDate:{},
        tClientInfo: {},

	},
	methods: {
        openDeptLayer:function(){
            layer.open({
                type: 1,
                //offset: '200px',
                skin: 'layui-layer-molv',
                title: "请选择小区",
                area: ['420px', '500px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptLayer"),
                btn: ['确定'],
                btn1: function (index) {
                    //vm.reload();
                    layer.close(index);
                }
            });
        },
        getDataDate: function(){
            vm.q.date1 = '';
            $.get(baseURL + "water/prodataanalyse/listdate",{proName:vm.q.dept}, function(r){
                vm.dataDate = r.page;
                //console.log(vm.dataDate);
                if(vm.dataDate.length > 0){
                    vm.q.date1 = vm.dataDate[0];
                    vm.query();
                }
            });
        },
        getDeptTreeLeft: function(){
            $.get(baseURL + "water/waterdept/queryDeptAll", function(r){
                //console.log(r);
                ztree = $.fn.zTree.init($("#deptTreeLeft"), settingLeft, r);
                fuzzySearch('deptTreeLeft','#treeSearchKey',null,true);
                var node = ztree.getNodeByParam("deptId", vm.q.dept);
                if(node != null){
                    ztree.selectNode(node);
                    vm.q.dept = node.deptId;
                }
                var temp=ztree.getNodes();
                getNum(ztree,temp);

                ztree.expandAll(true);
            })
        },
        initData:function (){
            vm.q.cid = null;
            vm.q.cname = null;
            vm.q.caddr = null;
            vm.q.cstatus = '';
            vm.q.deviceId = null;
            vm.q.date1 = vm.dataDate.length > 0 ? vm.dataDate[0] : '';
            vm.query();
        },
		query: function () {
            vm.newpage=true;
			vm.reload();
		},
		getInfo: function(clientId){
            var clientIds = getSelectedRows();
            if(clientIds == null){
                return ;
            }

            $("#jqGrid").jqGrid('resetSelection');
            $("#jqGrid").jqGrid('setSelection',clientIds);

            vm.proData =$("#jqGrid").jqGrid("getRowData", clientIds);
		},
        outxls: function(){
            var total = $("#jqGrid").jqGrid('getGridParam', 'records') + "";
            var dept = vm.q.dept==null ? "" : vm.q.dept+  "";
            var url = baseURL
                + "water/prodata/export?params="
                + encodeURIComponent(JSON.stringify({
                    pro_name:vm.q.dept,
                    clientId:vm.q.cid,
                    clientName:vm.q.cname,
                    clientAddress:vm.q.caddr,
                    deviceStatus:vm.q.cstatus,
                    deviceId:vm.q.deviceId,
                    nowDate:vm.q.date1,
                    limit:total,page:"1"}));

            //console.log(decodeURIComponent(url));
            location.href = url;
        },
        updateClientInfo1: function (event) {
            $('#btnSaveOrUpdate1').button('loading').delay(1000).queue(function() {
                if (vm.tClientInfo.deviceId == null) return;
                layer.confirm('确定要保存修改的信息吗？', {
                    btn: ['保存','放弃'] //按钮
                }, function(){
                    vm.tClientInfo.desc1=$('#datetimepicker1').val();

                    var url = "water/tclientinfo/update1";
                    $.ajax({
                        type: "POST",
                        url: baseURL + url,
                        contentType: "application/json",
                        data: JSON.stringify(vm.tClientInfo),
                        success: function(r){
                            if(r.code === 0){
                                layer.msg("操作成功", {icon: 1});
                                vm.newpage=false;
                                vm.reload();
                                $('#btnSaveOrUpdate1').button('reset');
                                $('#btnSaveOrUpdate1').dequeue();
                            }else{
                                layer.alert(r.msg);
                                $('#btnSaveOrUpdate1').button('reset');
                                $('#btnSaveOrUpdate1').dequeue();
                            }
                        }
                    });
                },function(){
                    $('#btnSaveOrUpdate').button('reset');
                    $('#btnSaveOrUpdate').dequeue();
                });
            });
        },
        updateClientInfo: function (event) {
            $('#btnSaveOrUpdate').button('loading').delay(1000).queue(function() {
                if (vm.tClientInfo.deviceId == null) return;
                    layer.confirm('确定要保存修改的信息吗？', {
                        btn: ['保存','放弃'] //按钮
                    }, function(){
                        vm.tClientInfo.desc1=$('#datetimepicker1').val();

                        var url = "water/tclientinfo/update";
                        $.ajax({
                            type: "POST",
                            url: baseURL + url,
                            contentType: "application/json",
                            data: JSON.stringify(vm.tClientInfo),
                            success: function(r){
                                if(r.code === 0){
                                    layer.msg("操作成功", {icon: 1});
                                    vm.newpage=false;
                                    vm.reload();
                                    $('#btnSaveOrUpdate').button('reset');
                                    $('#btnSaveOrUpdate').dequeue();
                                }else{
                                    layer.alert(r.msg);
                                    $('#btnSaveOrUpdate').button('reset');
                                    $('#btnSaveOrUpdate').dequeue();
                                }
                            }
                        });
                    },function(){
                        $('#btnSaveOrUpdate').button('reset');
                        $('#btnSaveOrUpdate').dequeue();
                    });
            });
        },
        openInfoLayer :function(event){
            $.get(baseURL + "water/tclientinfo/info/"+event.deviceId, function(r){
                vm.tClientInfo = r.tClientInfo;
                $('#datetimepicker1').datetimepicker('setDate',vm.tClientInfo.desc1 != "" ? vm.tClientInfo.desc1 : moment(Date.now()).format("YYYY-MM-DD"));

                vm.proData = event;
                layer.open({
                    type: 1,
                    //offset: '50px',
                    skin: 'layui-layer-molv',
                    title: "详细信息处理 【"+event.clientName + "】【" +event.clientAddress+"】",
                    area: ['600px', '550px'],
                    shade: 0,
                    shadeClose: false,
                    content: jQuery("#infoLayer"),
                    btn: ['关闭'],
                });
            });
        },
		reload: function (event) {
            //console.log(vm.q);
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
            if(vm.newpage){page = "1";}

			$("#jqGrid").jqGrid('setGridParam',{
                postData:{
                    'pro_name':vm.q.dept,
                    'clientId':vm.q.cid,
                    'clientName':vm.q.cname,
                    'clientAddress':vm.q.caddr,
                    'deviceStatus':vm.q.cstatus,
                    'deviceId':vm.q.deviceId,
                    'nowDate':vm.q.date1,
                },
                page:page
            }).trigger("reloadGrid");
		}
	},
    created: function(){
        this.getDeptTreeLeft();
    }
});